<template>
    <div class="flex flex-col item-center bg-white ml-64 w-full min-h-screen p-8">
        <div>
            <h2 class="text-center text-3xl font-extrabold text-gray-900 mb-8">
                历史问答记录
            </h2>
        </div>
        <!--查询条件-->
        <div class="flex items-center">
            <!--关键词-->
            <div class="p-4 mx-10">
                <label>关键词：</label>
                <el-input v-model="questionPageQueryDTO.keyWord" style="width: 240px" placeholder="请输入关键词" clearable />
            </div>
            <!--日期限制-->
            <div class="p-4 mx-24">
                <label>起止时间：</label>
                <el-date-picker v-model="dateDuration" type="datetimerange" start-placeholder="开始时间" :size="'large'"
                    clearable end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </div>
            <div class="p-4 mx-24">
                <el-button @click="getQuestionRecords" type="primary" round>搜索</el-button>
                <el-button @click="clickBatchDeleteButton" type="danger" round>
                    <span v-if="!batchDeleteButton">批量删除</span>
                    <span v-else>确认删除</span>
                </el-button>
            </div>
        </div>
        <el-divider content-position="left">table</el-divider>
        <div>
            <el-table ref="tableRef" :data="questionRecords.recordList" style="width: 100%"
                :default-sort="{ prop: 'id', order: 'ascending' }" @selection-change="handleSelectionChange">
                <el-table-column v-if="batchDeleteButton" type="selection" width="55" />
                <el-table-column fixed prop="id" label="记录id" width="180" sortable />
                <el-table-column prop="sessionId" label="会话id" width="300" />
                <el-table-column prop="content" label="提问内容" width="300" />
                <el-table-column prop="inputToken" label="输入token" width="150" sortable />
                <el-table-column prop="outputToken" label="输出token" width="150" sortable />
                <el-table-column prop="createTime" label="提问时间" width="180" sortable />
                <el-table-column fixed="right" label="Operations" min-width="120">
                    <template #default="scope">
                        <el-popover placement="right" :width="750" trigger="click">
                            <template #reference>
                                <el-button size="small" type="primary" plain
                                    @click="handleDetail(scope.row.id)">详情</el-button>
                            </template>
                            <el-table :data="questionDetail">
                                <el-table-column width="600" property="answer" label="回答" />
                                <el-table-column width="100" label="引用文件" class="flex">
                                    <template #default="scope">
                                        <div v-for="(url, index) in scope.row.srcUrls" :key="index">
                                            <img :src="url" alt="图片"
                                                class="mt-1 w-20 h-20 object-cover cursor-pointer transform transition-transform hover:scale-105" />
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-popover>
                        <el-button size="small" type="danger" plain @click="handleDelete(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-divider content-position="right">pagination</el-divider>
        <!--分页-->
        <div class="demo-pagination-block mt-3">
            <el-pagination v-model:current-page="questionPageQueryDTO.page" style="justify-content: center;"
                v-model:page-size="questionPageQueryDTO.pageSize" :page-sizes="[1, 5, 10, 20]" :size="'large'"
                :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
                :total="questionRecords.total" @size-change="getQuestionRecords" @current-change="getQuestionRecords" />
        </div>

    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useHistoryApi } from '../../../api/history';
import { useAdminInfoStore } from '../../../store';
import { ElMessage } from 'element-plus';

// 查询时间段
const dateDuration = ref(null);
// 选中id
const multipleSelection = ref([]);
// 批量删除按钮flag
const batchDeleteButton = ref(false);
// 批量删除按钮点击事件
const clickBatchDeleteButton = () => {
    if (batchDeleteButton.value == false) {
        batchDeleteButton.value = true;
    } else {
        if (multipleSelection.value.length === 0) {
            ElMessage.error("删除列表为空，未删除任何记录");
        } else {
            historyApi.deleteBatchRecords(multipleSelection.value.join(',')).then(response => {
                if (response.data.code == 1) {
                    ElMessage.success("删除成功！");
                    // 更新记录
                    getQuestionRecords();
                } else {
                    ElMessage.error(response.data.message);
                }
            }).catch(error => {
                console.error(error);
            })
        }
        // 还原状态
        batchDeleteButton.value = false;
        multipleSelection.value = [];
        tableRef.value.clearSelection();
    }
}
// 将id传入数组
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val.map((item: { id: String; }) => item.id);
};

// 表格绑定元素
const tableRef = ref();

// 问题记录
const questionRecords = ref({
    total: 0,
    recordList: [],
});
const historyApi = new useHistoryApi();
const adminStore = useAdminInfoStore();

// 问题详情
const questionDetail = ref([{
    answer: '',
    srcUrls: []
}])

const questionPageQueryDTO = ref({
    userId: adminStore.getId,
    page: 1,
    pageSize: 10,
    keyWord: null,
    begin: null,
    end: null,
})

// 请求记录
const getQuestionRecords = () => {
    if (dateDuration.value != null) {
        questionPageQueryDTO.value.begin = dateDuration.value[0];
        questionPageQueryDTO.value.end = dateDuration.value[1];
    }
    historyApi.getQuestionRecord(questionPageQueryDTO.value).then(response => {
        if (response.data.code == 1) {
            questionRecords.value.total = response.data.data.total;
            questionRecords.value.recordList = response.data.data.dataList;
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 删除按钮点击事件
const handleDelete = (id: String) => {
    historyApi.deleteBatchRecords(id).then(response => {
        if (response.data.code == 1) {
            ElMessage.success("删除成功！");
            // 刷新
            getQuestionRecords();
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 详情按钮点击事件
const handleDetail = (id: String) => {
    historyApi.getQuestionDetail(id).then(response => {
        if (response.data.code == 1) {
            // 格式处理
            let answer = response.data.data.answer.replace(/<ref>\[(\d+)\]<\/ref>/g, '');
            answer = answer.replace(/\n/g, '');
            questionDetail.value[0].answer = answer;
            questionDetail.value[0].srcUrls = response.data.data.sources;
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 挂载更新
onMounted(() => {
    getQuestionRecords();
});
</script>

<style scoped></style>